package com.baizhi.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@Aspect
public class CmfzSqlAop {

    @Resource
    private RedisTemplate redisTemplate;

    @Before("@annotation(com.baizhi.annotation.CmfzDMLAnnotation)")
    public void before(JoinPoint joinPoint) {
        String target = joinPoint.getTarget().getClass().getName();
        redisTemplate.delete(target);
    }

    @Around("@annotation(com.baizhi.annotation.CmfzDQLAnnotation)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(methodName);
        for (int i = 0; i < args.length; i++) {
            stringBuffer.append(args[i]);
        }
        HashOperations hashOperations = redisTemplate.opsForHash();
        Object result = hashOperations.get(className,stringBuffer.toString());
        if(result==null){
            System.out.println("查询数据库=============");
            result = joinPoint.proceed();
            Map map = new HashMap<>();
            map.put(stringBuffer.toString(), result);
            hashOperations.putAll(className, map);
        }
        System.out.println("缓存取值=============");
        return result;
    }

}
